<template>
  <NForm
    ref="formRef"
    :model="formData"
    :rules="rules"
    :label-width="labelWidth"
    :label-placement="labelPlacement"
  >
    <slot :form-data="formData" :form-ref="formRef" />
  </NForm>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';

interface Props {
  /** 表单数据 */
  formData: Record<string, any>;
  /** 表单验证规则 */
  rules?: FormRules;
  /** 标签宽度 */
  labelWidth?: number | string;
  /** 标签位置 */
  labelPlacement?: 'left' | 'top';
}

withDefaults(defineProps<Props>(), {
  labelWidth: 100,
  labelPlacement: 'left'
});

const formRef = ref<FormInst | null>(null);

/** 验证表单 */
const validate = async () => {
  if (!formRef.value) return false;
  try {
    await formRef.value.validate();
    return true;
  } catch {
    return false;
  }
};

/** 重置表单 */
const reset = () => {
  formRef.value?.restoreValidation();
};

defineExpose({
  validate,
  reset,
  formRef
});
</script>
